<script setup>
import { ref } from 'vue'
import { Delete, Edit } from '@element-plus/icons-vue'

import ChannelSelect from './components/ChannelSelect.vue'
import { artDelService } from '@/api/article'
import { commodityGetListService } from '@/api/commodity'
import { formatTime } from '@/utils/format'
import ArticleEdit from './components/CommodityEdit.vue'
const articleList = ref([])
const params = ref({
  pageNo: 1,
  pageSize: 5
})
const paramsReset = ref({
  pageNo: 1,
  pageSize: 5,
  name: '',
  status: null,
  sortId: null
})

const loading = ref(false)
const total = ref(0)
const getArticleList = async () => {
  loading.value = true
  const res = await commodityGetListService(params.value)
  articleList.value = res.data.data.list
  total.value = res.data.data.total
  loading.value = false
}
getArticleList()
const handleSizeChange = (page) => {
  articleList.value.pageSize = page
  getArticleList()
}
const handleCurrentChange = (page) => {
  articleList.value.pagenum = page
  getArticleList()
}
const edit = ref(null)
const openAddart = () => {
  edit.value.open({})
}
const onEditChannel = (row) => {
  edit.value.open(row)
  
  
}
// 添加修改成功
const onSuccess = (type) => {
  if (type === 'add') {
    // 如果是添加，需要跳转渲染最后一页，编辑直接渲染当前页
    const lastPage = Math.ceil((total.value + 1) / params.value.pagesize)
    params.value.pagenum = lastPage
  }
  getArticleList()
}
const search = () => {
  getArticleList()
}
const reset = () => {
  params.value = {}
  getArticleList()
}
/**
 * 删除文章信息
 * @param {Object} row - 要删除的文章的信息对象
 * @description 显示确认对话框，询问用户是否确认删除文章信息。如果确认，则调用artDelService服务删除文章，并在删除成功后显示提示消息，并重新获取文章列表。
 */
const onDelChannel = async (row) => {
  try {
    // 显示确认对话框，询问用户是否确认删除文章信息
    await ElMessageBox.confirm('你确认删除该文章信息吗？', '温馨提示', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })

    // 调用artDelService服务删除文章
    const deletionResult = await artDelService(row.id)

    // 检查服务调用结果
    if (deletionResult) {
      // 显示删除成功的提示消息
      ElMessage({ type: 'success', message: '删除成功' })
      // 重新获取文章列表
      await getArticleList()
    } else {
      // 如果删除失败，给出提示
      ElMessage({ type: 'error', message: '删除失败，请重试' })
    }
  } catch (error) {
    // 异常处理：捕获确认对话框取消操作或其他异常
    console.error('删除文章时发生错误:', error)
    // 可选：根据错误类型给出不同的用户提示
    ElMessage({ type: 'info', message: '删除操作已取消或遇到问题，请重试' })
  }
}

</script>

<template>
  <page-Container title="商品管理">
    <template #extra>
      <el-button type="primary" @click="openAddart">添加商品</el-button>
    </template>

    <el-form :inline="true" :model="params">
      <el-form-item>
        <ChannelSelect name="商品分类" v-model="params.sortId"></ChannelSelect>
      </el-form-item>
      <!-- <ChannelSelect name="文章分类" v-model="modelValue"></ChannelSelect> -->
      <el-form-item label="商品状态">
        <el-select placeholder="请选择文章状态" v-model="params.status">
          <el-option label="上架" value="1" />
          <el-option label="下架" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="商品名称">
        <el-input
          placeholder="商品名称"
          v-model="params.name"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="search" type="primary">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="articleList" style="width: 100%">
      <el-table-column prop="name" show-overflow-tooltip label="商品名称" />
      <el-table-column label="商品图片">
        <template #default="scope">
            <img :src="scope.row.image" alt="" style="width: 50px; height: 50px;">
          </template>
      </el-table-column>
      <el-table-column prop="sortName" label="商品分类" />
      <el-table-column prop="csortName" label="商品子分类" />
      <el-table-column prop="number" label="库存" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="sale" label="销量" />
      <el-table-column prop="create_time" width="150px" label="发布时间">
        <template #default="{ row }">
          {{ formatTime(row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" >
        <template #default="scope">
            <el-tag type="success" v-if="scope.row.status === '1'">已发布</el-tag>
            <el-tag type="primary" v-if="scope.row.status === '0'">未发布</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            @click="onEditChannel(row)"
            type="primary"
            :icon="Edit"
            circle
            plain
          >
          </el-button>

          <el-button
            @click="onDelChannel(row)"
            type="danger"
            :icon="Delete"
            circle
            plain
          ></el-button>
        </template>
      </el-table-column>

      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-pagination
      v-model:current-page="params.pageNo"
      v-model:page-size="params.pageSize"
      :page-sizes="[5, 7, 10]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <ArticleEdit ref="edit" @success="onSuccess"></ArticleEdit>
  </page-Container>
</template>
<style scoped>
.el-select {
  --el-select-width: 180px;
}
</style>
